const moment = require("moment");
const utils = require("../utils/index");
const { poolQuery } = require("../utils/db");
const menuModel = require("../models/menuModel");
const menuService = {
  checkIsChild: (req) => {
    return new Promise((resolve, reject) => {
      poolQuery(menuModel.checkParentId, [req.params.id], (err, rows) => {
        if (err) {
          reject(err);
        }
        if (rows.length !== 0) {
          reject("存在子集数据,请先删除所有子集");
        }
        resolve();
      });
    });
  },
  addMenu: (req, res) => {
    const params = {
      ...req.body,
      create_time: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    poolQuery(menuModel.add, params, (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("菜单添加失败");
      return res.tip("菜单添加成功", 0);
    });
  },
  // 编辑菜单时检查父级id 不能为本身或子集
  checkMovedMenu: (req) => {
    return new Promise((resolve, reject) => {
      const { id, parent_id } = req.body;
      if (id === parent_id) reject("不能移动到本身");
      poolQuery(menuModel.checkParentId, [id], (err, rows) => {
        if (err) reject(err);
        const ids = rows.map((item) => item.id);
        if (ids.includes(parent_id)) reject("不能移动到子集");
        resolve();
      });
    });
  },
  editMenu: (req, res) => {
    console.log(12312);
    if (req.body.parent_id === "") {
      req.body.parent_id = null;
    }
    delete req.body.create_time;
    poolQuery(menuModel.editMenu, [req.body, req.body.id], (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("菜单修改失败");
      return res.tip("菜单修改成功", 0);
    });
  },
  deleteMenu: (req, res) => {
    console.log(req.params);
    poolQuery(menuModel.deleteMenu, [req.params.id], (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("菜单删除失败");
      return res.tip("菜单删除成功", 0);
    });
  },
  //获取菜单列表
  getMenuTreeList: (req, res) => {
    const { account } = req.user;
    poolQuery(menuModel.list, (err, data) => {
      if (err) return res.tip(err);
      return res.send({
        code: 0,
        data:
          account === "admin"
            ? utils.arrToRouterTree(data)
            : utils.specialRouterTree(data), // 返回权限列表用 只返回菜单列表信息
        message: "成功获取菜单列表",
      });
    });
  },
};

module.exports = menuService;
